package com.baozun.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.baozun.model.TContact;
import com.baozun.model.TContactExample;
import com.baozun.model.TContactExample.Criteria;
import com.baozun.model.TUser;
import com.baozun.service.ContactService;
import com.baozun.util.AjaxUtil;
import com.baozun.util.CommonConst;
import com.baozun.util.ContactUtil;
import com.baozun.util.DataEncapsulation;
import com.baozun.util.ModelMapUtil;
import com.baozun.util.PageData;
import com.baozun.util.StringUtil;
import com.baozun.util.WebUtil;

/**
 * 
 * @Title:
 * @Company:宝尊电子商务有限公司
 * @Description:
 * @Author:xiaozhou.zhou
 * @Since:2015年1月6日
 * @Copyright:Copyright (c) 2014
 * @ModifyDate:
 * @Version:1.1.0
 */
@Controller
@RequestMapping("/contact")
public class ContactController {
    Logger logger = LoggerFactory.getLogger(ContactController.class);
    @Autowired
    @Qualifier("contactService")
    private ContactService contactService;
    private int pageSize = 20;
    private int currentPage = 1;

    @RequestMapping("/contact_main")
    public String contactMain(HttpServletRequest request, HttpServletResponse response) {
        return "contact/contact_main";
    }

    @RequestMapping("/contact_list")
    public ModelAndView contactList(HttpServletRequest request, HttpServletResponse response) {
        String nameOrUnit = request.getParameter("name_or_unit");
        String pageSizeStr = request.getParameter("pageSize");
        String currentPageStr = request.getParameter("currentPage");
        pageSize = StringUtil.getIntFromStr(pageSizeStr, pageSize);
        currentPage = StringUtil.getIntFromStr(currentPageStr, currentPage);
        // 从数据库中查询所有该用户相关的联系人，其中有个人所属联系人，以及其它用户的公开联系人
        // 从此处可以得到查询条件为stUserId=user.getStUserId or stIsOpen = '1';
        // 从session中取出当前登录用户
        TUser user = (TUser) request.getSession().getAttribute(CommonConst.SESSION_USER);

        TContactExample record = new TContactExample();
        if (StringUtils.isNotEmpty(nameOrUnit)) {
            // 如果查询条件不为空，按条件进行查询
            Criteria criteria = record.createCriteria();
            criteria.andStContactNameLike("%"+nameOrUnit+"%");
            record.or(record.createCriteria().andStUnitNameLike("%"+nameOrUnit+"%"));
        }
        // 默认条件
        Criteria defaultCriteria = record.createCriteria();
        defaultCriteria.andStUserIdEqualTo(user.getStUserId());
        record.or(record.createCriteria().andStIsOpenEqualTo(CommonConst.BOOLEAN_VALUE_TRUE_STR));

        String order = TContact.DT_CREATE_TIME + " desc";
        record.setOrderByClause(order);
        PageData<TContact> pageData = contactService.getPageListByExample(record, pageSize, currentPage);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("pageData", pageData);
        return new ModelAndView("contact/contact_list", model);
    }

    /**
     * 新增
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/contact_add")
    public ModelAndView contactAdd(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("contact/contact_add");
    }

    /**
     * 编辑
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/contact_edit")
    public ModelAndView contactEdit(HttpServletRequest request, HttpServletResponse response) {
        String stContactId = request.getParameter(TContact.ST_CONTACT_ID);
        TContact contact = (TContact) contactService.get(stContactId);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(TContact.T_CONTACT, contact);
        return new ModelAndView("contact/contact_edit", model);
    }

    /**
     * 新增或编辑提交
     * 
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/contact_save")
    public String contactSave(ModelMap model, HttpServletRequest request) {
        try {
            TContact contact = DataEncapsulation.request2Bean(request, TContact.class);
            contactService.update(contact);
            // 上下文中的联系人进行更新
            flushContext(request, contact, "update");
            model.put("msg", WebUtil.encodeURL("更新成功！"));
            model.put("jsm", "workLater");
        } catch (Exception e) {
            model.put("msg", WebUtil.encodeURL("更新失败！"));
            model.put("jsm", "workLater");
            logger.error("##ERROR contact save is error errorStackTrace:[{}];errorMessage:[{}]",e.getStackTrace(),e.getMessage());
        }
        return "include/refresh"; 
    }

    /**
     * 新增或编辑提交
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/contact_add_submit")
    public String contactAddSubmit(ModelMap model,HttpServletRequest request, HttpServletResponse response) {
        try {
            TContact contact = DataEncapsulation.request2Bean(request, TContact.class);
            contactService.add(contact);
            // 上下文中的联系人进行更新
            flushContext(request, contact, "update");
            new ModelMapUtil(model).put("msg", WebUtil.encodeURL("新增成功！")).put("jsm", "workLater");
        } catch (Exception e) {
            e.printStackTrace();
            new ModelMapUtil(model).put("msg", WebUtil.encodeURL("新增失败！")).put("jsm", "workLater");
        }
        return "include/refresh";
    }

    /**
     * 刷新上下文中联系人
     * 
     * @param request
     * @param contact
     */
    private void flushContext(HttpServletRequest request, TContact contact, String type) {
        // TODO Auto-generated method stub
        String key = contact.getStContactId();
        if ("update".equals(type)) {
            ContactUtil.updateContextList(request, CommonConst.CONTEXT_CONTACT_LIST, contact, TContact.class);
            ContactUtil.updateContextMap(request, CommonConst.CONTEXT_CONTACT_MAP, key, contact);
        } else if ("delete".equals(type)) {
            ContactUtil.delete(request, CommonConst.CONTEXT_CONTACT_LIST, contact, TContact.class);
            ContactUtil.delete(request, CommonConst.CONTEXT_CONTACT_MAP, key);
        }
    }

    /**
     * 删除
     * 
     * @param request
     * @param response
     */
    @RequestMapping("/contact_delete")
    public void contactDelete(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = AjaxUtil.getWriter(request, response);
        try {
            String stContactId = request.getParameter("stContactId");
            TContact contact = (TContact) contactService.get(stContactId);
            contactService.delete(stContactId);
            flushContext(request, contact, "delete");
            out.print(CommonConst.AJAX_RIGHT);
        } catch (Exception e) {
            e.printStackTrace();
            out.print(CommonConst.AJAX_ERROR);
        }
        out.flush();
        out.close();
    }

    /**
     * 联系人更新
     * 
     * @param request
     * @param response
     */
    @RequestMapping("/contact_flush")
    public void contactFlush(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = AjaxUtil.getWriter(request, response);
        @SuppressWarnings("unchecked")
        List<TContact> contactList = (List<TContact>) request.getSession().getServletContext().getAttribute(CommonConst.CONTEXT_CONTACT_LIST);
        JSONArray json = JSONArray.fromObject(contactList);
        out.print(json.toString());
    }
}
